package cc.mango.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * ProjectName：webServerController Class Name：DataBase Class Detail：
 * Createor：hunter Create Time：Jan 11, 2012 6:00:15 PM Modifier：hunter Modify
 * Date：Jan 11, 2012 6:00:15 PM Modify Detail：
 *
 * @version
 *
 */
public class DataBase
{
	private static final Log		log		= LogFactory
											.getLog(DataBase.class);
	private Connection			connection;
	private PreparedStatement	prepstmt	= null;
	private ResultSet			rs;

	public Connection getConnection()
	{
		return connection;
	}

	public void setConnection(Connection connection)
	{
		this.connection = connection;
	}

	public DataBase(Connection connection)
	{
		this.connection = connection;
	}

	public void CloseAll()
	{
		try
		{
			if (rs != null)
			{
				rs.close();
			}
			if (prepstmt != null)
			{
				prepstmt.close();
			}
			if (connection != null && !connection.isClosed())
			{
				connection.close();
			}
		}
		catch (Exception e)
		{

		}
	}

	public int saveOrUpdateOrDelete(String sql, Object... objs)
	{
		try
		{
			prepstmt = connection.prepareStatement(sql);
			for (int i = 0; i < objs.length; i++)
			{
				prepstmt.setObject(i + 1, objs[i]);
			}
			prepstmt.executeUpdate();

		}
		catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;

	}

	public ResultSet query(String sql, Object... objs)
	{
		try
		{
			prepstmt = connection.prepareStatement(sql);
			for (int i = 0; i < objs.length; i++)
			{
				prepstmt.setObject(i + 1, objs[i]);
			}
			rs = prepstmt.executeQuery();
		}
		catch (Exception e)
		{
			return null;
		}
		return rs;
	}

	public static void main(String[] args) throws SQLException
	{
		DataBase db = new DataBase(ConnectionPool.getConnection());
		log.debug(db.getConnection().isClosed());
		ResultSet rs = db.query("select * from notify_message_history");
		while (rs.next())
		{
			log.debug(rs.getObject("account"));
		}
		db.CloseAll();
	}
}